package com.mmtech.edb.data.handler.impl;

import com.google.common.collect.Maps;
import com.mmtech.edb.data.config.DataSendConfig;
import com.mmtech.edb.data.handler.DataHandler;
import com.mmtech.edb.data.model.User;
import com.mmtech.edb.data.service.DataService;
import com.mmtech.edb.data.util.ExcelExportUtil;
import com.mmtech.edb.data.util.PlaceholderUtil;
import com.mmtech.mail.service.MailService;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 发送数据
 *
 * @author wuchong
 * @since 2019-07-15 15:02
 **/
@Profile({"prod"})
@Component
public class DataHandlerImpl implements DataHandler {

    static {
        System.setProperty("mail.mime.splitlongparameters", "false");
        System.setProperty("mail.mime.charset", "UTF-8");
    }

    private final DataService<User> dataService;

    private final MailService mailService;

    private final DataSendConfig dataSendConfig;

    private final TemplateEngine templateEngine;

    private ResourceLoader resourceLoader = new DefaultResourceLoader();

    @Autowired
    public DataHandlerImpl(DataService<User> dataService, MailService mailService, DataSendConfig dataSendConfig, TemplateEngine templateEngine) {
        this.dataService = dataService;
        this.mailService = mailService;
        this.dataSendConfig = dataSendConfig;
        this.templateEngine = templateEngine;
    }

    /**
     * 处理数据
     */
    public void process() throws IOException, InvalidFormatException {

        // 第一步，产生数据
        // T-1
        String yesterday = DateTime.now().minusDays(1).toString("yyyy-MM-dd");
        String startDate = StringUtils.defaultIfEmpty(dataSendConfig.getStartDate(), yesterday);
        String endDate = StringUtils.defaultIfEmpty(dataSendConfig.getEndDate(), yesterday);

        String date = assembleDate(startDate, endDate);
        Map<String, String> params = new HashMap<>();
        params.put("date", date);
        // 查询数据库生产数据
        List<User> datas = dataService.produce("", startDate, endDate);

        // 第二步，根据数据生成附件
        // 附件模板
        String attachmentTemplate = dataSendConfig.getAttachmentTemplate();
        InputStream attachmentTemplateIs = resourceLoader.getResource(attachmentTemplate).getInputStream();
        // 附件名
        String attachment = PlaceholderUtil.replace(dataSendConfig.getAttachment(), params, "{", "}");
        // 根据模板生成附件
        Map<String, Object> beanParams = Maps.newHashMap();
        beanParams.put("list", datas);
        byte[] bytes = ExcelExportUtil.createExcelBytes(attachmentTemplateIs, beanParams);

        // 第三步，发送邮件
        String[] to = StringUtils.split(dataSendConfig.getTo(), ",");
        String[] cc = StringUtils.isEmpty(dataSendConfig.getCc()) ? null : StringUtils.split(dataSendConfig.getCc(), ",");
        // 邮件主题
        String subject = PlaceholderUtil.replace(dataSendConfig.getSubject(), params, "{", "}");
        //创建邮件正文
        Context context = new Context();
        context.setVariables(params);
        String content = templateEngine.process(dataSendConfig.getContentTemplate(), context);
        // 发送邮件
        mailService.sendAttachmentsMail(to, cc, subject, content, attachment, bytes);
    }

}
